package com.song.security.service.impl;

import com.song.security.entity.User;
import com.song.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.queryByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("未知账号");
        }
        String password = passwordEncoder.encode(user.getPassword());
        //构建认证用户明细
        return new org.springframework.security.core.userdetails.User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin,ROLE_user,/user/add"));
    }
}
